// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import { TextEncoder } from 'util';
import * as vscode from 'vscode';

// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
	
	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "helloworld" is now active!');

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('helloworld.helloWorld', () => {
		// The code you place here will be executed every time your command is executed
		// Display a message box to the user
		console.log('this is in command.');
		const currentEditor = vscode.window.activeTextEditor;
		currentEditor?.edit((editBuilder) => {
			const current_pos = currentEditor.selection.start.line;
			console.log('selection.line:', current_pos);
			let document = currentEditor.document;
			let begin = undefined;
			let end = undefined;
			let space_num;
			let space = '';
			for(let i = current_pos; i >= 0; --i){
				if(document.lineAt(i).text.trim().startsWith('def')){
					space_num = document.lineAt(i).text.indexOf('def') + 1
					for(let j = 0; j < space_num; ++j){
						space += ' ';
					}
					begin = new vscode.Position(i, 0);
					break;
				}
			}
			if(begin == undefined){
				vscode.window.showWarningMessage('Current cursor is not in function')
				return;
			}
			console.log('lines:', currentEditor.document.lineCount);
			for(let i = begin?.line + 1; i < currentEditor.document.lineCount; ++i){
				console.log(document.lineAt(i).text);
				if(document.lineAt(i).text.startsWith(space) || document.lineAt(i).text.trim() == ''){
					continue;
				}
				else{
					end = new vscode.Position(i, 0);
					break;
				}
			}
			if(end == undefined){
				end = new vscode.Position(document.lineCount - 1, 0)
			}
			console.log('begin.line:', begin?.line);
			console.log('begin.end:', end?.line);
			editBuilder.delete(new vscode.Range(begin, end));
		})
	});

	context.subscriptions.push(disposable);
}

// this method is called when your extension is deactivated
export function deactivate() {
	vscode.window.showInformationMessage('this plugion is deactiavte.')
}
